package com.vint.lintcode;

import com.vint.common.ListNode;

import java.util.Collections;
import java.util.Comparator;

/**
 * 判断链表是否有环
 */
public class Lintcode102 {
	public boolean hasCycle(ListNode head) {
		if (null == head) {
			return false;
		}
	    ListNode first = head;
		ListNode two = head;
		if (head.next == head) {
		    return true;
        }
        if (null == head.next) {
		    return false;
        }
        two = head.next;
		while(null != first && null != two) {
		    if (first == two) {
		        return true;
            }
            first = first.next;
		    if (null == two.next) {
		        return false;
            }
            two = two.next.next;
		}
		return false;
	}

	public static void main(String[] args) {
	    ListNode head = new ListNode(1);
        ListNode head1 = new ListNode(1);
        ListNode head2 = new ListNode(1);
        ListNode head3 = new ListNode(1);
        head.next = head1;
        head1.next = head2;
        head2.next = head3;
        head3.next = head1;
        Lintcode102 lintcode102 = new Lintcode102();
        System.out.println(lintcode102.hasCycle(head));
	}
}
